package com.videoweb.domain.conversation.entity;

import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * Message实体
 * 对话中的单条消息
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message {
    
    private Long id;
    private Long conversationId;
    private String role; // user, assistant, system, tool
    private String content;
    private String contentType; // text, code, image, file
    private Integer tokenCount;
    private String modelUsed;
    private Map<String, Object> toolCalls; // 工具调用信息
    private Map<String, Object> metadata; // 元数据
    private Long parentMessageId; // 父消息ID（用于消息链）
    private LocalDateTime createdAt;
    
    /**
     * 创建用户消息
     */
    public static Message createUserMessage(String content) {
        return Message.builder()
                .role("user")
                .content(content)
                .contentType("text")
                .tokenCount(estimateTokenCount(content))
                .createdAt(LocalDateTime.now())
                .build();
    }
    
    /**
     * 创建助手消息
     */
    public static Message createAssistantMessage(String content, String modelUsed) {
        return Message.builder()
                .role("assistant")
                .content(content)
                .contentType("text")
                .tokenCount(estimateTokenCount(content))
                .modelUsed(modelUsed)
                .createdAt(LocalDateTime.now())
                .build();
    }
    
    /**
     * 创建系统消息
     */
    public static Message createSystemMessage(String content) {
        return Message.builder()
                .role("system")
                .content(content)
                .contentType("text")
                .tokenCount(estimateTokenCount(content))
                .createdAt(LocalDateTime.now())
                .build();
    }
    
    /**
     * 创建代码消息
     */
    public static Message createCodeMessage(String content, String language) {
        Message message = Message.builder()
                .role("assistant")
                .content(content)
                .contentType("code")
                .tokenCount(estimateTokenCount(content))
                .createdAt(LocalDateTime.now())
                .build();
        
        // 在元数据中保存编程语言信息
        if (language != null) {
            message.addMetadata("language", language);
        }
        
        return message;
    }
    
    /**
     * 创建工具调用消息
     */
    public static Message createToolCallMessage(String toolName, Map<String, Object> parameters) {
        return Message.builder()
                .role("tool")
                .content("Tool call: " + toolName)
                .contentType("text")
                .toolCalls(Map.of(
                    "tool_name", toolName,
                    "parameters", parameters
                ))
                .tokenCount(50) // 工具调用的默认token数
                .createdAt(LocalDateTime.now())
                .build();
    }
    
    /**
     * 检查是否为用户消息
     */
    public boolean isUserMessage() {
        return "user".equals(this.role);
    }
    
    /**
     * 检查是否为助手消息
     */
    public boolean isAssistantMessage() {
        return "assistant".equals(this.role);
    }
    
    /**
     * 检查是否为代码消息
     */
    public boolean isCodeMessage() {
        return "code".equals(this.contentType);
    }
    
    /**
     * 检查是否为工具调用消息
     */
    public boolean isToolCallMessage() {
        return "tool".equals(this.role) || (this.toolCalls != null && !this.toolCalls.isEmpty());
    }
    
    /**
     * 添加元数据
     */
    public void addMetadata(String key, Object value) {
        if (this.metadata == null) {
            this.metadata = new java.util.HashMap<>();
        }
        this.metadata.put(key, value);
    }
    
    /**
     * 获取元数据
     */
    public Object getMetadata(String key) {
        return this.metadata != null ? this.metadata.get(key) : null;
    }
    
    /**
     * 设置父消息
     */
    public void setParent(Message parentMessage) {
        if (parentMessage != null) {
            this.parentMessageId = parentMessage.getId();
        }
    }
    
    /**
     * 验证消息数据
     */
    public boolean isValid() {
        return role != null && !role.trim().isEmpty()
            && content != null && !content.trim().isEmpty()
            && contentType != null && !contentType.trim().isEmpty()
            && createdAt != null;
    }
    
    /**
     * 简单的token数量估算
     * 中文字符按2个token计算，英文按0.75个token计算
     */
    private static Integer estimateTokenCount(String content) {
        if (content == null || content.isEmpty()) {
            return 0;
        }
        
        int chineseCount = 0;
        int englishCount = 0;
        
        for (char c : content.toCharArray()) {
            if (c >= 0x4e00 && c <= 0x9fff) {
                chineseCount++;
            } else {
                englishCount++;
            }
        }
        
        return (int) (chineseCount * 2 + englishCount * 0.75);
    }
    
    /**
     * 获取消息摘要（用于日志或显示）
     */
    public String getSummary() {
        if (content == null) {
            return "[Empty message]";
        }
        
        String summary = content.length() > 50 ? content.substring(0, 50) + "..." : content;
        return String.format("[%s] %s", role.toUpperCase(), summary);
    }
}